<template>
  <div class="contract-audit-page">
    <!-- 返回按钮 -->
    <div class="back-button-wrapper">
      <button class="back-button" @click="goBack">
        ← 返回聊天
      </button>
    </div>
    
    <div class="audit-container">
      <!-- 左侧：代码输入区 -->
      <div class="input-section">
        <div class="section-header">
          <h3>🔒 智能合约代码输入</h3>
          <div class="header-actions">
            <button class="btn ghost" @click="clearCode">清空</button>
          </div>
        </div>

        <div class="code-editor-wrapper">
          <textarea
            v-model="sourceCode"
            class="code-editor"
            placeholder="请粘贴 Solidity 智能合约源码...

例如:
pragma solidity ^0.8.0;

contract MyContract {
    // 您的合约代码
}"
            spellcheck="false"
          ></textarea>
          <div class="editor-footer">
            <span class="code-stats">{{ codeStats }}</span>
          </div>
        </div>

        <div class="action-bar">
          <button 
            class="btn primary large" 
            :disabled="!canAnalyze || analyzing" 
            @click="analyzeContract"
          >
            <span v-if="!analyzing">🔍 开始安全审计</span>
            <span v-else>⏳ 分析中...</span>
          </button>
        </div>
      </div>

      <!-- 右侧：分析结果区 -->
      <div class="result-section">
        <div class="section-header">
          <h3>📊 审计报告</h3>
          <div class="header-actions" v-if="hasResult">
            <button class="btn ghost" @click="copyReport">📋 复制报告</button>
            <button class="btn ghost" @click="downloadReport">💾 下载报告</button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!hasResult && !analyzing && !error" class="empty-state">
          <div class="empty-icon">🛡️</div>
          <p class="empty-title">等待分析</p>
          <p class="empty-desc">请在左侧输入智能合约代码，然后点击"开始安全审计"</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="analyzing" class="loading-state">
          <div class="loading-spinner"></div>
          <p>正在使用 AI 深度分析合约安全性...</p>
          <p class="loading-hint">这可能需要几秒钟时间</p>
        </div>

        <!-- 错误状态 -->
        <div v-if="error" class="error-state">
          <div class="error-icon">❌</div>
          <p class="error-title">分析失败</p>
          <p class="error-message">{{ error }}</p>
          <button class="btn primary" @click="error = ''">确定</button>
        </div>

        <!-- 结果展示 -->
        <div v-if="hasResult && !analyzing" class="result-content">


          <!-- 风险统计 -->
          <div class="stats-grid" v-if="auditResult && auditResult.findings && auditResult.findings.length > 0">
            <div class="stat-card high">
              <div class="stat-number">{{ countBySeverity('High') }}</div>
              <div class="stat-label">🔴 高危</div>
            </div>
            <div class="stat-card medium">
              <div class="stat-number">{{ countBySeverity('Medium') }}</div>
              <div class="stat-label">🟠 中危</div>
            </div>
            <div class="stat-card low">
              <div class="stat-number">{{ countBySeverity('Low') }}</div>
              <div class="stat-label">🟡 低危</div>
            </div>
            <div class="stat-card info">
              <div class="stat-number">{{ countBySeverity('Info') }}</div>
              <div class="stat-label">🔵 信息</div>
            </div>
          </div>

          <!-- 发现项列表 -->
          <div class="findings-section" v-if="auditResult && auditResult.findings && auditResult.findings.length > 0">
            <h4>🔍 详细发现 ({{ auditResult.findings.length }})</h4>
            <div 
              v-for="(finding, index) in auditResult.findings" 
              :key="index" 
              class="finding-card"
              :class="finding.severity.toLowerCase()"
            >
              <div class="finding-header">
                <span class="severity-badge" :class="finding.severity.toLowerCase()">
                  {{ getSeverityEmoji(finding.severity) }} {{ finding.severity }}
                </span>
                <span class="swc-badge" v-if="finding.swcId">{{ finding.swcId }}</span>
              </div>
              <h5 class="finding-title">{{ index + 1 }}. {{ finding.title }}</h5>
              <p class="finding-desc">{{ finding.description }}</p>
              
              <div class="finding-evidence" v-if="finding.evidence && finding.evidence.lines && finding.evidence.lines.length > 0">
                <strong>📍 证据行号:</strong> {{ finding.evidence.lines.join(', ') }}
              </div>
              
              <div class="finding-recommendation">
                <strong>💡 修复建议:</strong>
                <p>{{ finding.recommendation }}</p>
              </div>
              
              <div class="finding-confidence" v-if="finding.confidence">
                <div class="confidence-bar">
                  <div class="confidence-fill" :style="{ width: (finding.confidence * 100) + '%' }"></div>
                </div>
                <span class="confidence-text">置信度: {{ (finding.confidence * 100).toFixed(0) }}%</span>
              </div>
            </div>
          </div>



          <!-- Markdown完整报告 -->
          <div class="markdown-report" v-if="auditResult">
            <h4>📄 完整报告</h4>
            <div class="markdown-content">
              <MarkdownRenderer :content="auditResult.report_markdown || ''" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { API_BASE_URL } from '@/config/api';
import MarkdownRenderer from '@/components/MarkdownRenderer.vue';

const router = useRouter();

interface Finding {
  swcId: string;
  title: string;
  severity: 'High' | 'Medium' | 'Low' | 'Info';
  description: string;
  evidence?: {
    lines: number[];
    snippets: string[];
  };
  recommendation: string;
  confidence?: number;
}

interface AuditResult {
  success: boolean;
  summary: string;
  status?: string;
  findings: Finding[];
  report_markdown: string;
  test_mode: boolean;
  has_vulnerability?: boolean;
  timestamp: string;
}

const sourceCode = ref('');
const analyzing = ref(false);
const auditResult = ref<AuditResult | null>(null);
const error = ref('');

const canAnalyze = computed(() => {
  return sourceCode.value.trim().length >= 10;
});

const hasResult = computed(() => {
  return auditResult.value !== null;
});

const codeStats = computed(() => {
  const lines = sourceCode.value.split('\n').length;
  const chars = sourceCode.value.length;
  return `${lines} 行 | ${chars} 字符`;
});

const countBySeverity = (severity: string): number => {
  if (!auditResult.value?.findings) return 0;
  return auditResult.value.findings.filter(f => f.severity === severity).length;
};

const getSeverityEmoji = (severity: string): string => {
  const emojiMap: Record<string, string> = {
    'High': '🔴',
    'Medium': '🟠',
    'Low': '🟡',
    'Info': '🔵'
  };
  return emojiMap[severity] || '⚪';
};

const analyzeContract = async () => {
  if (!canAnalyze.value || analyzing.value) return;

  analyzing.value = true;
  error.value = '';
  auditResult.value = null;

  try {
    const response = await fetch(`${API_BASE_URL}/api/contract/analyze`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        source_code: sourceCode.value
      })
    });

    // 检查响应状态
    if (!response.ok) {
      const errorText = await response.text();
      console.error('HTTP错误响应:', response.status, errorText);
      throw new Error(`HTTP ${response.status}: ${errorText}`);
    }

    const data = await response.json();
    console.log('后端返回的完整数据:', data);
    console.log('data.success:', data.success);
    console.log('data.data:', data.data);

    // 检查响应格式
    if (!data) {
      throw new Error('后端返回数据为空');
    }

    // 检查success字段
    if (data.success === false) {
      throw new Error(data.error || '分析失败');
    }

    // 检查data字段是否存在
    if (!data.data) {
      console.error('后端返回数据缺少data字段:', data);
      throw new Error('后端返回数据格式错误：缺少data字段');
    }

    // 映射后端返回的 report 字段到 report_markdown
    auditResult.value = {
      success: true,
      summary: data.data?.summary || data.data?.status || '合约安全审计完成',
      status: data.data?.status || '审计完成',
      findings: data.data?.findings || [],
      report_markdown: data.data?.report || data.data?.report_markdown || '暂无报告内容',
      test_mode: data.data?.test_mode || false,
      has_vulnerability: data.data?.has_vulnerability || false,
      timestamp: data.data?.timestamp || new Date().toISOString()
    };

    console.log('auditResult设置完成:', auditResult.value);
  } catch (err: any) {
    console.error('Contract analysis error:', err);
    error.value = err.message || '分析失败，请稍后重试';
    // 确保在错误时也清除加载状态
    analyzing.value = false;
  } finally {
    // 确保无论如何都清除加载状态
    analyzing.value = false;
  }
};

const clearCode = () => {
  sourceCode.value = '';
  auditResult.value = null;
  error.value = '';
};

const copyReport = async () => {
  if (!auditResult.value?.report_markdown) return;
  
  try {
    await navigator.clipboard.writeText(auditResult.value.report_markdown);
    alert('报告已复制到剪贴板！');
  } catch (err) {
    console.error('Failed to copy:', err);
  }
};

const downloadReport = () => {
  if (!auditResult.value?.report_markdown) return;
  
  const blob = new Blob([auditResult.value.report_markdown], { type: 'text/markdown' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `contract-audit-${new Date().getTime()}.md`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const goBack = () => {
  router.push('/chat');
};
</script>

<style scoped>
.contract-audit-page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.back-button-wrapper {
  padding: 8px 0;
  border-bottom: 1px solid var(--border);
}

.back-button {
  padding: 8px 16px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--card);
  color: var(--foreground);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.back-button:hover {
  background: var(--muted);
}

.audit-container {
  flex: 1;
  overflow: hidden;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px 0;
}

.input-section, .result-section {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--card);
  border: 1px solid var(--border);
  border-radius: 12px;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border);
  background: var(--muted);
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.code-editor-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.code-editor {
  flex: 1;
  width: 100%;
  padding: 16px;
  border: none;
  background: var(--background);
  color: var(--foreground);
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  font-size: 13px;
  line-height: 1.6;
  resize: none;
  overflow-y: auto;
}

.code-editor:focus {
  outline: none;
}

.editor-footer {
  padding: 8px 16px;
  border-top: 1px solid var(--border);
  background: var(--muted);
  font-size: 12px;
  color: var(--muted-foreground);
}

.action-bar {
  padding: 16px 20px;
  border-top: 1px solid var(--border);
  display: flex;
  justify-content: center;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: 1px solid var(--border);
  background: var(--card);
  color: var(--foreground);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn:hover:not(:disabled) {
  background: var(--muted);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn.primary {
  background: hsl(221, 83%, 53%);
  color: white;
  border-color: hsl(221, 83%, 53%);
}

.btn.primary:hover:not(:disabled) {
  background: hsl(221, 83%, 45%);
}

.btn.secondary {
  background: var(--secondary);
  color: var(--secondary-foreground);
}

.btn.ghost {
  background: transparent;
  border-color: transparent;
}

.btn.large {
  padding: 12px 32px;
  font-size: 16px;
  font-weight: 600;
}

.result-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-state, .loading-state, .error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.empty-icon, .error-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-title, .error-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}

.empty-desc {
  color: var(--muted-foreground);
  max-width: 300px;
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid var(--border);
  border-top-color: hsl(221, 83%, 53%);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-hint {
  color: var(--muted-foreground);
  font-size: 14px;
  margin-top: 8px;
}

.error-message {
  color: var(--destructive);
  margin-bottom: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.stat-card {
  background: var(--card);
  border: 2px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.stat-card.high { border-color: hsl(0, 84%, 60%); }
.stat-card.medium { border-color: hsl(25, 95%, 53%); }
.stat-card.low { border-color: hsl(48, 96%, 53%); }
.stat-card.info { border-color: hsl(217, 91%, 60%); }

.stat-number {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--muted-foreground);
}

.findings-section {
  margin-bottom: 20px;
}

.findings-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
}

.finding-card {
  background: var(--card);
  border: 1px solid var(--border);
  border-left: 4px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.finding-card.high { border-left-color: hsl(0, 84%, 60%); }
.finding-card.medium { border-left-color: hsl(25, 95%, 53%); }
.finding-card.low { border-left-color: hsl(48, 96%, 53%); }
.finding-card.info { border-left-color: hsl(217, 91%, 60%); }

.finding-header {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.severity-badge, .swc-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.severity-badge.high { background: hsla(0, 84%, 60%, 0.1); color: hsl(0, 84%, 40%); }
.severity-badge.medium { background: hsla(25, 95%, 53%, 0.1); color: hsl(25, 95%, 40%); }
.severity-badge.low { background: hsla(48, 96%, 53%, 0.1); color: hsl(48, 96%, 40%); }
.severity-badge.info { background: hsla(217, 91%, 60%, 0.1); color: hsl(217, 91%, 40%); }

.swc-badge {
  background: var(--muted);
  color: var(--muted-foreground);
}

.finding-title {
  margin: 0 0 8px 0;
  font-size: 15px;
  font-weight: 600;
}

.finding-desc {
  margin: 0 0 12px 0;
  line-height: 1.6;
  color: var(--muted-foreground);
}

.finding-evidence, .finding-recommendation {
  margin-bottom: 12px;
  font-size: 14px;
}

.finding-recommendation p {
  margin: 4px 0 0 0;
  padding: 8px;
  background: var(--muted);
  border-radius: 4px;
}

.finding-confidence {
  display: flex;
  align-items: center;
  gap: 12px;
}

.confidence-bar {
  flex: 1;
  height: 8px;
  background: var(--muted);
  border-radius: 4px;
  overflow: hidden;
}

.confidence-fill {
  height: 100%;
  background: hsl(142, 76%, 36%);
  transition: width 0.3s;
}

.confidence-text {
  font-size: 12px;
  color: var(--muted-foreground);
  white-space: nowrap;
}

.markdown-report {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border);
}

.markdown-report h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
}

.markdown-content {
  background: var(--muted);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  max-height: 500px;
  overflow-y: auto;
}

/* 响应式 */
@media (max-width: 1200px) {
  .audit-container {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr;
  }
  
  .input-section {
    max-height: 400px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

